并发编程

并发引入

并发的需要

image-20231218134311212

image-20231218134400978

并发的问题

image-20231218134204083

基本的并发方法

image-20240106143910657

Process-based

并发编程

image-20231218133732272

优劣分析

  1. Pros

    • Handle multiple connections concurrently

    • Clean sharing model

    • Simple and straightforward

  2. Cons

    • Additional overhead for process control

    • Nontrivial to share data between processesIPC

并发服务器

  1. 基本思想

    image-20231218134445259

  2. 代码实现

Event-based

并发编程

实现对于fd数组的维护+select调用

image-20240106144746819

并发服务器

 

Thread-based

并发编程

image-20240106145132526

image-20231218141822615

image-20231218141926908

image-20231218142135784

创建线程

终止线程

回收线程

分离线程

初始化线程

并发服务器

image-20231218144649209

共享变量

image-20240106145345842

image-20231218145025820

无意识共享问题

image-20231218144719671

image-20231218144817674

image-20231218144847751

信号量同步

循环体拆分

L,U,S

image-20240106145627287

image-20240106145639349

进度图

image-20240106145950630

信号量

image-20240106150010243

image-20240106150224142

调度共享资源

生产者-消费者问题

image-20240106150237376

 

读者-写者问题

image-20240106150352663

 

其它并发问题

性能刻画

 

线程安全

  1. 不保护共享变量的的函数

  2. 保持跨越多个调用的状态的函数

  3. 返回指向静态变量的指针的函数

  4. 调用线程不安全函数的函数

image-20240106150618410

可重入性

竞争

死锁

image-20240106151037340